package com.lvmama.pangolin.timer.processor;


import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.busi.timer.TimerManager;
import com.lvmama.pangolin.busi.timer.TimerManagerAssist;
import com.lvmama.pangolin.common.*;
import com.lvmama.pangolin.entity.LogVO;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.entity.lmm.LMMCareProduct;
import com.lvmama.pangolin.entity.lmm.LMMTicketCommodity;
import com.lvmama.pangolin.entity.lmm.LMMTicketCommodityPrice;
import com.lvmama.pangolin.entity.lmm.LMMTicketProduct;
import com.lvmama.pangolin.hbaseutil.HBaseUtils;
import com.lvmama.pangolin.lmm.service.LMMCareProductService;
import com.lvmama.pangolin.lmm.service.LMMTicketProductService;
import com.lvmama.pangolin.service.OperLogService;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.HttpSignUtil;
import com.lvmama.pangolin.util.HttpsUtil;
import com.lvmama.pangolin.util.SpringContextUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
* @ClassName: QueryLvmmProduct 
* @Description: TODO 定时获取驴妈妈产品数据
* @author yuanchi
* @date 2017年3月7日 上午10:16:08
 */
public class SynLMMTicketProduct extends CommonJob {

	@Autowired
	private LMMTicketProductService productService;
	@Autowired
	private LMMCareProductService careProductService;
	
	@Autowired
	private OperLogService operLogService;
	
	@Autowired
	private TimerService timerService;
	
	@Autowired
	private HBaseUtils hBaseUtils;
	
	private Logger logger = Logger.getLogger(SynLMMTicketProduct.class);
	
	private String url = "http://api3g2.lvmama.com/nticket/router/rest.do?";
	
	private  Date TimerDate = null; 
	
	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		logger.info("-----------同步LMM产品数据开始-----------");
		
		String configParam = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.JOB_DATAKEY);
		String task_id = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.TASK_ID);
		String timerId = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.TIMER_ID);
		String timerCode = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.TIMER_CODE);
		String syscode=System.getProperties().getProperty("SYSCODE");
		syscode = StringTools.isValid(syscode)?syscode:"PUBLIC";
		
		
		ConfigManager config = ConfigManager.getInstance();
		url = config.getParamValue(configParam, "URL"
				,"http://api3g2.lvmama.com/nticket/router/rest.do?");
		
		if(careProductService == null)
		{
			careProductService = (LMMCareProductService) SpringContextUtil
					.getBean(LMMCareProductService.class);
		}
		if(timerService == null)
		{
			timerService = (TimerService) SpringContextUtil
					.getBean(TimerService.class);
		}
		//保存产品信息
		if (productService == null)
		{
			productService = (LMMTicketProductService) SpringContextUtil
					.getBean(LMMTicketProductService.class);
		}
		//获取timer最新信息
		Timer timer = new Timer();
		timer.setTimer_id(timerId);
		timer.setSyscode(syscode);
		List<Timer> timerList = timerService.queryTimerList(timer);
		String message = null;
		LMMCareProduct record = new LMMCareProduct();
		List<LMMCareProduct> prodList = null;
		boolean sucessFlag = false;
		if(timerList != null && timerList.size() > 0)
		{
			Timer timerVO = timerList.get(0);
			int runNum = timerVO.getRun_num();
			int retryNum = timerVO.getRetry_num();
			String status = timerVO.getTimer_status();
			TimerDate = timerVO.getCreate_time();
			if(TimerDate == null)
			{
				TimerDate = new Date();
			}
			record.setDealFlag(0);
			record.setBusinessCode("TICKET");
			if("0".equals(status))
			{
				if(runNum == 0)
				{
					//任务第一次执行，产品表处理标识统一改成0，任务执行次数默认+1
					timerService.updateRunNumByCon(timerId);
					careProductService.updateDealFlag(record);
				}
				else if (runNum < retryNum)
				{
					//任务执行次数+1
					timerService.updateRunNumByCon(timerId);
				}
				//获取处理标识为0的所有产品信息
				prodList = careProductService.selectByCond(record);
				if(runNum>=retryNum)
				{
					
					//记录异常日志
					if(prodList != null && !prodList.isEmpty())
					{
						message = "任务已经重试最大次数，依然存在产品信息同步异常导致产品信息未同步成功！任务默认成功。";
						logger.error("任务已经重试最大次数，依然存在产品信息同步异常导致产品信息未同步成功！");
						prodList.clear();
						//默认成功
						sucessFlag = true;
					}
					
				}
				
			}
		}
		//存在需要同步查询的产品信息
		int errorCount = 0;
		int successCount = 0;
		if(prodList != null && !prodList.isEmpty())
		{
			LMMTicketProduct product = null;
			List<LMMTicketCommodity> commodityList = null;
			
			for (LMMCareProduct careProduct : prodList)
			{
				try
				{
					String prodId = careProduct.getProductId();
					//获取产品信息
					product = transferProdData(prodId,task_id,timerCode);
					if(product == null)
					{
						continue ;
					}
					product.setTaskId(task_id);
					//获取商品列表信息
					commodityList = transferCommodityData(prodId,task_id);
					if(commodityList != null && !commodityList.isEmpty())
					{
						int commoditySum = commodityList.size();
						int packageNum = 0;
						int preferentialNum = 0;
						int commodityTypeNum = 0;
						String paramvale = config.getParamValue("SYN_LMM_TICKET_PRODUCT", "PACK_COMMODITY_TYPE","组合套餐");
						Set<String> typeSet = new HashSet<String>();
						for (LMMTicketCommodity commodity : commodityList)
						{
							commodity.setNewGrabTime(TimerDate);
							//获取商品价格信息
//							transferCommodityPriceData(commodity,configParam);
							//优惠数量
							if(StringTools.isValid(commodity.getPreferentialInfo()))
							{
								preferentialNum ++;
							}
							//打包产品数量
							if(paramvale.contains(commodity.getCommodityType()))
							{
								packageNum ++;
							}
							typeSet.add(commodity.getCommodityType());
							List<LMMTicketCommodityPrice> priceList = new ArrayList<LMMTicketCommodityPrice>();
							LMMTicketCommodityPrice price = new LMMTicketCommodityPrice();
							price.setSalePrice(commodity.getSalePrice());
							price.setGrabTime(commodity.getNewGrabTime());
							price.setTaskId(commodity.getTaskId());
							price.setSaleDate(commodity.getNewGrabTime());
							price.setSaleStrDate(DateUtil.yyyyMMdd_NOT_.format(price.getGrabTime()));
							priceList.add(price);
							commodity.setPriceList(priceList);
							
							sleep(100);
			
						}
						
						commodityTypeNum = typeSet.size();
						product.setCommodityNum(commoditySum);
						product.setCommPackageNum(packageNum);
						product.setCommPreferentialNum(preferentialNum);
						product.setCommTypeNum(commodityTypeNum);
						
					}
					
					productService.saveProductInfo(product,commodityList,TimerDate);
					saveDataToHbase(product,commodityList);
					record.setDealFlag(1);
					record.setProductId(prodId);
					careProductService.updateDealFlag(record);
					successCount ++;
					sleep(1000);
				}catch (Exception e)
				{
					logger.error(careProduct.toString(),e);
					errorCount ++;
				}
				
			}
			
		}
		if(!sucessFlag)
		{
			//获取处理标识为0的所有产品信息.二次检查
			record.setDealFlag(0);
			record.setProductId(null);
			prodList = careProductService.selectByCond(record);
			if(prodList == null || prodList.isEmpty())
			{
				sucessFlag = true;
			}
		}
		
		if(sucessFlag)
		{
			try
			{
				message = message != null ? message:"SUCESS";
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("timer_status", "5");
				param.put("error_desc", message);
				param.put("timer_id", timerId);
//				param.put("oper_time", timerId);
				timerService.updateTimerByCon(param);
				new TimerManagerAssist().removeJob(timerCode);
			}
			catch (Exception e)
			{
			}
		}
		message = message != null ? message: "同步产品数据完成,successCount : " 
				+ successCount + " errorCount ：" + errorCount ;
		logger.info(message);
		logger.info("-----------同步LMM产品数据结束-----------");
		
		
		
	}
	
	
	private void sleep(long milliseconds)
	{
		try
		{
			Thread.sleep(milliseconds);
		}
		catch (InterruptedException e)
		{
		}
	}
	
	private void saveDataToHbase(LMMTicketProduct prod,List<LMMTicketCommodity> commodityList)
	{
		if(prod != null)
		{
			Map<String,String> map = new HashMap<String,String>();
			map.put("task_id", prod.getTaskId());
			map.put("insert_time", DateUtil.yyyyMMdd_NOT_.format(prod.getNewGrabTime()));
			map.put("product_id", prod.getProductId());
			map.put("scenery_name", prod.getSceneryName());
			map.put("scenery_addr", prod.getSceneryAddr());
			map.put("city_code", prod.getCityCode());
			map.put("detail_url", prod.getDetailUrl());
			map.put("lowest_price", prod.getLowestPrice());
			map.put("score", prod.getScore());
			map.put("image_num", prod.getImageNum());
			map.put("introduction", prod.getIntroduction());
			map.put("score_tag", prod.getScoreTag());
			map.put("sale_count", prod.getSaleCount());
			map.put("star_level", prod.getStarLevel());
			map.put("commodity_num", prod.getCommodityNum()+"");
			map.put("comm_preferential_num", prod.getCommPreferentialNum()+"");
			map.put("comm_package_num", prod.getCommPackageNum()+"");
			map.put("comm_type_num", prod.getCommTypeNum()+"");
			String rowkey = RowkeyGenerator.generateRowkey(prod.getProductId(), 
					TimerDate, prod.getTaskId());
			//保存产品信息
			if (hBaseUtils == null)
			{
				hBaseUtils = (HBaseUtils) SpringContextUtil
						.getBean(HBaseUtils.class);
			}
			hBaseUtils.save(map, Constant.TICKET_PRODUCT_H_LMM, Constant.HB_VARIABLE_FAMILY, rowkey);
		}
		if(commodityList != null && !commodityList.isEmpty())
		{
			for (LMMTicketCommodity commodity : commodityList)
			{
				
				Map<String,String> map = new HashMap<String,String>();
				map.put("task_id", commodity.getTaskId());
				map.put("insert_time", DateUtil.yyyyMMdd_NOT_.format(commodity.getNewGrabTime()));
				map.put("product_id", commodity.getProductId());
				map.put("commodity_id", commodity.getCommodityId());
				map.put("commodity_name", commodity.getCommodityName());
				map.put("commodity_type", commodity.getCommodityType());
				map.put("sale_cond", commodity.getSaleCond());
				map.put("refund_cond", commodity.getRefundCond());
				map.put("rack_rate", commodity.getRackRate());
				map.put("sale_price", commodity.getSalePrice());
				map.put("preferential_info", commodity.getPreferentialInfo());
				map.put("composite_id", commodity.getCompositeId());
				map.put("efficient_time", commodity.getEfficientTime());
				String rowkey = RowkeyGenerator.generateCommodityRowkey(commodity.getCommodityId(),
						TimerDate, prod.getProductId());
				
				hBaseUtils.save(map, Constant.TICKET_COMMODITY_H_LMM, Constant.HB_VARIABLE_FAMILY, rowkey);
				savePriceList(commodity,prod.getProductId());
			}
		}
		
	}
	
	private void savePriceList(LMMTicketCommodity commodity,String productId)
	{
		List<LMMTicketCommodityPrice> priceList = commodity.getPriceList();
		if(priceList != null && !priceList.isEmpty())
		{
			Map<String,String> map = null;
			String rowkey = null;
			for (LMMTicketCommodityPrice price : priceList)
			{
				map = new HashMap<String,String>();
				map.put("task_id", price.getTaskId());
				map.put("commodity_id", commodity.getCommodityId());
				map.put("grab_time", DateUtil.yyyyMMdd_NOT_.format(price.getGrabTime()));
				map.put("sale_date", price.getSaleStrDate());
				map.put("sale_price", price.getSalePrice());
				rowkey = RowkeyGenerator.generateCommodityRowkey(commodity.getCommodityId(), 
						price.getSaleDate(), productId);
				
				hBaseUtils.save(map, Constant.TICKET_COMMODITY_PRICE_LMM, Constant.HB_VARIABLE_FAMILY, rowkey);
				
			}
		}
	}
	
	private  LMMTicketProduct transferProdData(String prodId,String task_id,String timerCode) throws Exception
	{
		//查询care配置对象
		LMMCareProduct currentCare = new LMMCareProduct();
		currentCare.setBusinessCode("TICKET");
		currentCare.setProductId(prodId);
		List<LMMCareProduct> list = careProductService.selectByCond(currentCare);
		if(list!=null && !list.isEmpty()){
			currentCare = list.get(0);
		}
		LMMTicketProduct product = new LMMTicketProduct();
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.ticket.product.getDetails");
		param.put("version", "1.0.0");
		param.put("productId", prodId);
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		String json = HttpsUtil.requestGet(requestURL);
		JSONObject jo = JSONUtil.getObject(json);
		if(jo!= null && "true".equals(jo.getString("success")))
		{
			JSONObject jsonData = jo.getJSONObject("data");
			product = new LMMTicketProduct();
			product.setProductId(prodId);
			if(jsonData.containsKey("address"))
			{
				product.setSceneryAddr(jsonData.getString("address"));
			}
			product.setSceneryName(jsonData.getString("productName"));
			JSONObject clientDestVo =  jsonData.getJSONObject("clientDestVo");
			//优先使用配置城市，即慧眼本地维护的城市（境外citycode是自定义的）
			if(currentCare!=null){
				product.setCityCode(currentCare.getCityCode());
			}else if(clientDestVo != null){
				product.setCityCode(clientDestVo.getString("districtId"));
			}
			if(jsonData.containsKey("sellPrice"))
			{
				product.setLowestPrice(jsonData.getString("sellPrice"));
			}
			if(jsonData.containsKey("star"))
			{
				product.setStarLevel(jsonData.getString("star"));
			}
			else
			{
				product.setStarLevel("暂无星级评定");
			}
			if(jsonData.containsKey("virtualSaleQuantity"))
			{
				product.setSaleCount(jsonData.getString("virtualSaleQuantity"));
			}
			if(jsonData.containsKey("commentScore"))
			{
				product.setScore(jsonData.getString("commentScore"));
			}
			if(jsonData.containsKey("clientImageBaseVos"))
			{
				JSONArray imageArr = jsonData.getJSONArray("clientImageBaseVos");
				if(imageArr != null && imageArr.size() > 0)
				{
					product.setImageNum(imageArr.size()+"");
				}
				else
				{
					product.setImageNum("0");
				}
				
			}
			
			product.setNewGrabTime(TimerDate);
			
			product.setTaskId("");
			
		}
		else
		{
			String errorMessage = jo.getString("message");
			insertLog(task_id,timerCode,prodId,requestURL,errorMessage);
			throw new Exception(errorMessage);
		}
		
		return product;
		
	}
	
	private void insertLog(String taskId,String timerCode,String product_id,String url,String  message)
	{
		try
		{
			LogVO log = new LogVO();
			log.setBatch_num(taskId);
			log.setTask_id(taskId);
			//任务生成异常
			log.setLog_type("F");
			log.setError_desc(message);
			log.setTimer_code(timerCode);
			log.setTask_date(new Date());
			log.setUrl(url);
			log.setProduct_id(product_id);
			log.setCompany_code("LMM_C_CODE");
			log.setBusi_type("门票");
			if(operLogService == null )
			{
				operLogService = (OperLogService) SpringContextUtil.getBean(OperLogService.class);
			}
			operLogService.insertOperLog(log);
		}
		catch (Exception e)
		{
			logger.error("插入日志表失败！",e);
		}
		logger.info("上次同类型任务未完成，请检查处理！");
	}
	
	private List<LMMTicketCommodity>  transferCommodityData(String prodId,String taskId)
	{
		List<LMMTicketCommodity> comodityList =  new ArrayList<LMMTicketCommodity>();
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.ticket.goods.getGoods");
		param.put("version", "1.0.0");
		param.put("bizCategoryId", "11");
		param.put("productId", prodId);
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		String json =  HttpsUtil.requestGet(requestURL);
		JSONObject jo = JSONUtil.getObject(json);
		JSONObject jsonData = jo.getJSONObject("data");
		if(jsonData != null)
		{
			JSONArray jsonArr = jsonData.getJSONArray("items");
			if(jsonArr != null && jsonArr.size() > 0)
			{
				JSONObject item = null;
				JSONArray itemDatas = null;
				for(int i=0;i<jsonArr.size();i++)
				{
					item = jsonArr.getJSONObject(i);
					if(item == null)
						continue;
					String commodityType = item.getString("itemName");
					itemDatas = item.getJSONArray("itemDatas");
					if(itemDatas != null && itemDatas.size() > 0)
					{
						LMMTicketCommodity commodity = null;
						JSONObject commodityData = null;
						JSONArray secondTagItems = null;
						for (int j = 0; j < itemDatas.size() ;j++)
						{
							commodityData = itemDatas.getJSONObject(j);
							if(!commodityData.containsKey("sellPrice"))
							{
								continue;
							}
							commodity= new LMMTicketCommodity();
							commodity.setProductId(prodId);
							commodity.setTaskId(taskId);
							commodity.setCommodityType(commodityType);
							commodity.setNewGrabTime(new Date());
//							commodity.setCreateTime(new Date());
							commodity.setRefundCond(commodityData.getString("refundType"));
							commodity.setRackRate(commodityData.getString("marketPrice"));
							commodity.setSalePrice(commodityData.getString("sellPrice"));
							commodity.setCommodityId(commodityData.getString("suppGoodsId"));
							commodity.setCommodityName(commodityData.getString("name"));
							commodity.setEfficientTime(commodityData.containsKey("passLimit") ? commodityData.getString("passLimit") : null);
							secondTagItems = commodityData.getJSONArray("secondTagItems");
							if(secondTagItems != null && secondTagItems.size() > 0)
							{
								JSONObject tagItems = null;
								for (int k =0 ;k< secondTagItems.size();k++)
								{
									tagItems = secondTagItems.getJSONObject(k);
									if("today".equals(tagItems.getString("tagType")))
									{
										commodity.setSaleCond(tagItems.getString("name"));;
										
									}else if("refund".equals(tagItems.getString("tagType")))
									{
										commodity.setPreferentialInfo(tagItems.getString("name"));
									}
									
								}
							}
							if(commodityData.containsKey("packageType") 
									&& "LVMAMA".equalsIgnoreCase(commodityData.getString("packageType")))
							{
								commodity.setPackageType(commodityData.getString("packageType"));
								commodity.setCompositeId(commodity.getCommodityId());
								commodity.setCommodityId(commodityData.getString("productId"));
							}
							comodityList.add(commodity);
							
						}
					}
				}
			}
			
		}
		
		return comodityList;
		
	}
	
	private void  transferCommodityPriceData(LMMTicketCommodity commodity,String configParam)
	{
		List<LMMTicketCommodityPrice> priceList = new ArrayList<LMMTicketCommodityPrice>();
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.ticket.goods.getPriceCalendar");
		param.put("version", "1.0.0");
		if(StringTools.isValid(commodity.getCompositeId()))
		{
			param.put("combProductId", commodity.getCommodityId());
		}
		else
		{
			param.put("goodsIds", commodity.getCommodityId());
		}
		
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		String json =  HttpsUtil.requestGet(requestURL);
		JSONObject jo = JSONUtil.getObject(json);
		if(jo!= null && "true".equals(jo.getString("success")))
		{
			JSONArray jsonData = jo.getJSONArray("data");
			if(jsonData != null && jsonData.size() > 0)
			{
				ConfigManager config = ConfigManager.getInstance();
				int dateSpan =  Integer.valueOf(config.getParamValue(configParam, "DATE_SPAN","7"));
				JSONObject data = null;
				LMMTicketCommodityPrice price = null;
				DateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd");
				sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
				String strDate = null;
				for (int i = 0;i< jsonData.size() && i< dateSpan;i++)
				{
					price = new LMMTicketCommodityPrice();
					data = jsonData.getJSONObject(i);
					price.setSalePrice(data.getString("sellPrice"));
					price.setGrabTime(new Date());
					price.setTaskId(commodity.getTaskId());
					strDate = data.getString("specDate");
					if(StringTools.isValid(strDate))
					{
						try
						{
							price.setSaleStrDate(strDate.replaceAll("-", ""));
							price.setSaleDate(sdf.parse(strDate));
						}
						catch (ParseException e)
						{
							continue;
						}
						
					}
					priceList.add(price);
				}
			}
			commodity.setPriceList(priceList);
		}
		else
		{
			logger.error("requestURL: " + requestURL + " 调用异常!");
		}
		
	}
	
}
